<template>
  <div class="memb-receipt">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="搜索字段">
          <el-select v-model="searchForm.field" placeholder="请选择搜索字段" style="width: 150px">
            <el-option label="收货人" value="consignee"></el-option>
            <el-option label="地区" value="area"></el-option>
            <el-option label="街道" value="street"></el-option>
            <el-option label="手机号" value="cellphone"></el-option>
            <el-option label="会员ID" value="membId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="搜索内容">
          <el-input v-model="searchForm.code" placeholder="请输入搜索内容" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-area">
      <el-button type="primary" @click="showAddDialog">新增收货地址</el-button>
      <el-button type="danger" @click="batchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="membId" label="会员ID" width="100"></el-table-column>
      <el-table-column prop="consignee" label="收货人" width="120"></el-table-column>
      <el-table-column prop="area" label="地区" width="150"></el-table-column>
      <el-table-column prop="street" label="街道地址" min-width="200"></el-table-column>
      <el-table-column prop="cellphone" label="手机号" width="130"></el-table-column>
      <el-table-column prop="defaultAddr" label="默认地址" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.defaultAddr === '1' ? 'success' : 'info'">
            {{ scope.row.defaultAddr === '1' ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRow(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px">
        <el-form-item label="会员ID" prop="membId">
          <el-input v-model.number="form.membId" placeholder="请输入会员ID"></el-input>
        </el-form-item>
        <el-form-item label="收货人" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="地区" prop="area">
          <el-input v-model="form.area" placeholder="请输入地区"></el-input>
        </el-form-item>
        <el-form-item label="街道地址" prop="street">
          <el-input v-model="form.street" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="cellphone">
          <el-input v-model="form.cellphone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="默认地址" prop="defaultAddr">
          <el-radio-group v-model="form.defaultAddr">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../../axios/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'MembReceipt',
  data() {
    return {
      // 搜索表单
      searchForm: {
        field: '',
        code: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 选中的行
      selectedIds: [],
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增收货地址',
      isEdit: false,
      // 表单
      form: {
        id: null,
        membId: null,
        consignee: '',
        area: '',
        street: '',
        cellphone: '',
        defaultAddr: '0'
      },
      // 表单验证规则
      rules: {
        membId: [
          { required: true, message: '请输入会员ID', trigger: 'blur' },
          { type: 'number', message: '会员ID必须为数字', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入地区', trigger: 'blur' }
        ],
        street: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const offset = (this.currentPage - 1) * this.pageSize
        const params = {
          limit: this.pageSize,
          offset: offset,
          field: this.searchForm.field,
          code: this.searchForm.code
        }
        const response = await axios.get('/memb-receipt/list', { params })
        this.tableData = response.data.rows
        this.total = response.data.total
      } catch (error) {
        ElMessage.error('加载数据失败：' + error.message)
      } finally {
        this.loading = false
      }
    },
    // 搜索
    search() {
      this.currentPage = 1
      this.loadData()
    },
    // 重置搜索
    reset() {
      this.searchForm = {
        field: '',
        code: ''
      }
      this.currentPage = 1
      this.loadData()
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadData()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadData()
    },
    // 选择改变
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增收货地址'
      this.isEdit = false
      this.dialogVisible = true
    },
    // 显示编辑对话框
    showEditDialog(row) {
      this.dialogTitle = '编辑收货地址'
      this.isEdit = true
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        membId: null,
        consignee: '',
        area: '',
        street: '',
        cellphone: '',
        defaultAddr: '0'
      }
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    // 提交表单
    async submitForm() {
      try {
        await this.$refs.formRef.validate()
        if (this.isEdit) {
          await axios.put('/memb-receipt', this.form)
          ElMessage.success('更新成功')
        } else {
          await axios.post('/memb-receipt', this.form)
          ElMessage.success('新增成功')
        }
        this.dialogVisible = false
        this.loadData()
      } catch (error) {
        if (error.message) {
          ElMessage.error('操作失败：' + error.message)
        }
      }
    },
    // 删除单行
    async deleteRow(id) {
      try {
        await ElMessageBox.confirm('确定要删除这条收货地址吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await axios.delete(`/memb-receipt/${id}`)
        ElMessage.success('删除成功')
        this.loadData()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + error.message)
        }
      }
    },
    // 批量删除
    async batchDelete() {
      if (this.selectedIds.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
      }
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${this.selectedIds.length} 条收货地址吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await axios.delete('/memb-receipt/batch', { data: this.selectedIds })
        ElMessage.success('批量删除成功')
        this.loadData()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败：' + error.message)
        }
      }
    }
  }
}
</script>

<style scoped>
.memb-receipt {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.action-area {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>